<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Bean\SupplierApiConfigBean;
use GuzzleHttp\Promise\PromiseInterface;
use http\Encoding\Stream\Deflate;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class Weilian extends AbstractApi
{

    /**
     * @param array $data
     * @return string
     */
    function queryToString(array $data): string
    {
        $result = '';
        foreach ($data as $key => $value) {
            if (!empty($value)) $result .= "&{$key}=${value}";
        }
        return substr($result, 1);
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    function sign(array $data, string $appKey): string
    {
        ksort($data);
        unset($data['sign']);
        $paramPattern = $this->queryToString($data);
        $base64_str = base64_encode($paramPattern);
        return md5(hash_hmac('sha1', $base64_str, $appKey, true));
    }

    /**
     * 公共参数
     *
     * @return array
     */
    protected function commonQuery(): array
    {
        return [
            'version' => '1.0.0',
            'timestamp' => time()
        ];
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'productsn'             => $bean->getGoodsId(), //商品编码
            'buy_num'               => $bean->getRechargeNum(),//充值数量,
            'serial_number'         => $bean->getOrderNo(), //订单号
            'callback_url'          => $bean->getNotifyUrl(), //异步回调地址
            'timestamp'             => time(), //时间戳
            $bean->getProductId()   => $bean->getAccount(),
            ... $this->commonQuery(),
        ];
        $array['sign'] = $this->sign($array, $bean->getPrivateKey());
        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('serial_number', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(true)->setRechargeSuccess($status == 2);
    }



    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        $data = $this->rechargeData($bean);
        return $this->httpClient($http)->withBasicAuth($bean->getSupplierNum(), $bean->getSecretKey())
            ->withHeader('X-Api-Version', '1.0.0')
            ->asJson()->post($config->recharge_url, $data);
    }
}
